﻿using Microsoft.Extensions.DependencyInjection;
using FluentValidation.AspNetCore;
using System.Reflection;
using Microsoft.AspNetCore.Mvc;
using FluentValidation;
using Newtonsoft.Json.Converters;
using Newtonsoft.Json.Serialization;
using Newtonsoft.Json;
using HSGD.Common;
using HSGD.Model.Common;

namespace HSGD.Extensions {
    public static class FluentValidationSetup {

        /// <summary>
        /// 统一注册缓存
        /// </summary>
        /// <param name="services"></param>
        public static IMvcBuilder AddConfigureApiBehaviorOptionsSetup(this IMvcBuilder builder) {
            builder.ConfigureApiBehaviorOptions(options => {
                options.InvalidModelStateResponseFactory = context => {
                    var errors = context.ModelState.Values
                             .SelectMany(v => v.Errors)
                             .Select(e => e.ErrorMessage);
                    return new BadRequestObjectResult(new MessageModel() { success = false, status = 400, data = errors });
                };
            }).AddNewtonsoftJson(options => {
                options.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
                options.SerializerSettings.ContractResolver = new DefaultContractResolver();
                options.SerializerSettings.DateFormatString = "MM/dd/yyyy HH:mm:ss";
                //options.SerializerSettings.NullValueHandling = NullValueHandling.Ignore;
                options.SerializerSettings.DateTimeZoneHandling = DateTimeZoneHandling.Local;
                options.SerializerSettings.Converters.Add(new StringEnumConverter());
                //将long类型转为string
                //options.SerializerSettings.Converters.Add(new NumberConverter(NumberConverterShip.Int64));
            }).AddControllersAsServices();
            //属性注入.
            /**
             * AddControllersAsServices(); 等同于下面的代码
             * builder.Services.Replace(ServiceDescriptor.Transient<IControllerActivator, ServiceBasedControllerActivator>());
             */

            var assemblysServices = Assembly.LoadFrom(Path.Combine(AppContext.BaseDirectory, ProjectDllFileName.MODEL_NAME));
            builder.Services.AddFluentValidationAutoValidation()
                .AddFluentValidationClientsideAdapters()
                .AddValidatorsFromAssembly(assemblysServices);
            return builder;
        }
    }

}